<template>
  <div>
    <div class="top">
      <el-input v-model="tableDataName" placeholder="请输入标题关键字" style="width:240px"></el-input>
      <el-button type="primary" @click="doFilter()">搜索</el-button>
      <el-button @click="doReset()">重置</el-button>
      <el-button @click="doadd()">新增</el-button>
      <div class="space">
        <el-table :data="tableData" border style="width:100%">
          <el-table-column sortable label="id" header-align="center" align="center" prop="id" v-if="false">
          </el-table-column>
          <el-table-column prop="questionnaireTheme" sortable label="主题" width="180" header-align="center"
            align="center">
          </el-table-column>
          <el-table-column prop="questionnaireTitle" sortable label="标题" width="180" header-align="center"
            align="center">
          </el-table-column>
          <el-table-column prop="questions" sortable label="问卷问题" width="280" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="createdAt" sortable label="创建时间" width="200" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="endTime" sortable label="结束时间" width="200" header-align="center" align="center">
          </el-table-column>
          <el-table-column label="多选" header-align="center" align="center" width="100">
            <el-checkbox></el-checkbox>
          </el-table-column>
          <el-table-column label="操作" header-align="center" align="center" width="250">
            <template slot-scope="scope">
              <el-button size="small" @click="handleEdit(index = scope.$index, scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click.native.prevent="deleteRow(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="space">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totalItems">
          </el-pagination>
        </div>

        <el-dialog title="修改内容" :visible.sync="dialogFormVisible">
          <el-form :inline="true" :model="form">

            <el-form-item label="主题" :label-width="formLabelWidth">
              <el-input v-model="form.questionnaireTheme" auto-complete="off"></el-input>
            </el-form-item>

            <el-form-item label="标题" :label-width="formLabelWidth">
              <el-input v-model="form.questionnaireTitle" auto-complete="off"></el-input>
            </el-form-item>

            <el-form-item label="问卷问题" :label-width="formLabelWidth">
              <el-input v-model="form.questions" auto-complete="off"></el-input>
            </el-form-item>

            <el-form-item label="创建时间" :label-width="formLabelWidth">
              <el-date-picker v-model="form.createdAt" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" :label-width="formLabelWidth">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>


            <!-- <el-form-item label="创建时间" :label-width="formLabelWidth">
              <el-date-picker v-model="form.createdAt" align="right" type="date" placeholder="选择日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" :label-width="formLabelWidth">
              <el-date-picker v-model="form.endTime" align="right" type="date" placeholder="选择日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item> -->

          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="updata">确定</el-button>
          </div>

        </el-dialog>
      </div>
    </div>

  </div>
</template>

<script>
// import axios from "axios";
import { GetSatisfactionList, DeleteSatisfaction, UpdateSatisfaction, AddSatisfaction } from "@/api/satisfactionApi";
// import { DatePicker } from "element-ui";

export default {
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,//控制dialog页面开关
      tableDataBegin: [],//get数据容器
      filtertableData: [],//页面数据过滤容器
      tableDataName: "",//查询关键字
      pageSize: 10,//每页信息条数上限
      currentPage: 1,//默认显示第几页
      form: {},//新增或修改数据容器
      formLabelWidth: "80px",
      totalItems: 10,
    }
  },

  mounted() {
    this.querry();
    // this.changeTime();
  },
  handleSelectionChange(val) {
    this.users.id = val;
    console.log("选中的数据集合为:", val);
  },
  methods: {
    //获取数据并渲染table
    querry() {
      //向后端发送情求
      GetSatisfactionList().then((res) => {
        var istable = []
        //取出数据并检查是否标记为已删除
        res.data.forEach((item) => {
          if (item.isDeleted === true) {
            item.isDeleted = "已删除"
          } else {
            item.isDeleted = "未删除"
            // console.log(item);
          }
          istable.push(item)
        });

        for (let index = 0; index < istable.length; index++) {
          istable[index].createdAt = formDate(istable[index].createdAt)
          istable[index].endTime = formDate(istable[index].endTime)

        }

        //将数据装入容器
        this.tableDataBegin = res.data;
        this.totalItems = istable.length;
        console.log(istable);
        this.totalItems = istable.length;
        if (this.totalItems > this.pageSize) {
          for (let index = 0; index < this.pageSize; index++) {
            this.tableData.push(istable[index]);
            console.log(this.tableData);
          }
        } else {
          this.tableData = istable;
        }
      });
    },

    // changeA(val) {
    // 	this.a = val
    // },

    // changeAFather() { // 谁来调用它？ 是子组件的业务操作
    //   this.$emit('change', val)
    // },



    //编辑信息，弹出信息对话框
    handleEdit(index) {
      this.form = this.tableData[index];
      this.currentIndex = index;
      this.dialogFormVisible = true;
    },

    //dialog页面内容
    doadd() {
      this.form = {
        questionnaireTheme: "",
        questionnaireTitle: "",
        questions: "",
        createdAt: "",
        endTime: ""
      };

      this.dialogFormVisible = true;
    },

    //取消键，设置弹出对话框为不可见 
    cancel() {
      this.dialogFormVisible = false;
    },



    // doadd() {
    //   console.log("先假装一下");
    // },

    updata() {
      var that = this;
      //id=undefined就新增，有id进来就编辑
      if (that.form.id === undefined) {
        that.form.endTime = converTimeOfHMS(that.form.endTime);
        that.form.createdAt = converTimeOfHMS(that.form.createdAt);
        AddSatisfaction({
          questionnaireTitle: that.form.questionnaireTitle,
          questionnaireTheme: that.form.questionnaireTheme,
          endTime: that.form.endTime,
          createdAt: that.form.createdAt
        }).then(function (res) {
          console.log(that.form.id);
          console.log(res);
        }).catch(function (err) {
          //请求失败
          console.log(err);
        })
        this.dialogFormVisible = false;
      }
      else {
        that.form.endTime = converTimeOfHMS(that.form.endTime);
        that.form.createdAt = converTimeOfHMS(that.form.createdAt);
        // console.log(that.form.endTime);
        // console.log(that.form.createdAt);
        UpdateSatisfaction(that.form.id, {
          id: that.form.id,
          questionnaireTitle: that.form.questionnaireTitle,
          questionnaireTheme: that.form.questionnaireTheme,
          endTime: that.form.endTime,
          createdAt: that.form.createdAt

        }).then(function (res) {
          console.log(that.form.questionnaireTitle);
          console.log(that.form.questionnaireTheme);
          console.log(that.form.endTime);
          console.log(that.form.createdAt);
          console.log(that.form.id);
          console.log(res);
          // if (res.data.code == 200) {
          //     window.location.reload();
          //     const loading = that.$loading({
          //         lock: true,
          //         text: "修改成功",
          //         spinner: "el-icon-loading",
          //         background: "rgba(0, 0, 0, 0.7)",
          //     });
          //     setTimeout(() => {
          //         loading.close();
          //     }, 1500);
          // }
        }

        ).catch(function (err) {
          //请求失败
          console.log(err);
        })
        this.dialogFormVisible = false;
      }
    },
    //删除部分
    deleteRow(id, row) {
      console.log(row.id)
      if (confirm("确定要删除吗") == true) {

        DeleteSatisfaction(row.id).then((res) => {
          window.location.reload();
          if (res.code === 400) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
      }
    },


    //重置table（刷新table数据）
    doReset() {
      this.tableDataEnd = [];
      this.tableDataName = "";
      this.filterTableDataEnd = [];
      this.tableDataBegin.forEach((value) => {
        if (value.questionnaireTitle) {
          if (value.questionnaireTitle.indexOf(this.questionnaireTitle) >= 0) {
            this.filterTableDataEnd.push(value);
            console.log(value);
          }
        }
      });

      this.tableDataName = "";
      this.currentPage = 1;
      this.totalItems = this.filterTableDataEnd.length;
      this.querry();
    },


    //过滤（查询当前table内数据），前端完成
    doFilter() {
      if (this.tableDataName == "") {
        this.$message.warning("查询条件不能为空！");
        this.tableDataName = "";
        return;
      }
      console.log(this.tableDataBegin);
      this.tableDataEnd = [];

      this.filterTableDataEnd = [];
      this.tableDataBegin.forEach((value) => {
        if (value.questionnaireTitle) {
          if (value.questionnaireTitle.indexOf(this.tableDataName) >= 0) {
            console.log(value.questionnaireTitle);
            this.filterTableDataEnd.push(value);
          }
        }
      });

      this.tableDataName = "";
      this.currentPage = 1;
      this.totalItems = this.filterTableDataEnd.length;
      //渲染表格,根据值
      this.currentChangePage(this.filterTableDataEnd);

      this.flag = true;
    },






    //每页展示条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.handleCurrentChange(1);
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      //需要判断是否检索
      if (!this.flag) {
        this.currentChangePage(this.tableDataBegin);
        console.log(this.tableData);
      } else {
        this.currentChangePage(this.filtertableData);
        console.log(this.tableData);
      }
    }, //组件自带监控当前页码

    //点击下一页
    currentChangePage(list) {
      let from = (this.currentPage - 1) * this.pageSize;
      let to = this.currentPage * this.pageSize;
      this.tableData = [];
      for (; from < to; from++) {
        if (list[from]) {
          this.tableData.push(list[from]);
        }
      }
    },




    // changeTime(Date) {
    //   var timezone = 8; //目标时区时间，东八区

    //   var offset_GMT = new Date.getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟

    //   // console.log(offset_GMT);

    //   var nowDate = new Date.getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数

    //   console.log(nowDate);

    //   var targetDate = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000);

    //   console.log("东8区现在是：" + targetDate);

    // }
    // renderHeader(h, parmas) {
    //   let a = [h('el-checkbox',{
    //     props:{
    //       size:"mini",
    //       type:"primary"
    //     },
    //     on:{
    //       click:()=>{
    //         this.renderAddRow();
    //       }
    //     }

    //   },'')];
    //   return h('div',a);
    // }
  }
}

// 核心代码，可自行封装
function converTimeOfHMS(date) {
  var json_date = new Date(date).toJSON();
  return new Date(new Date(json_date) + 8 * 3600 * 1000)
    .toISOString()
    .replace(/T/g, " ")
    .replace(/\.[\d]{3}Z/, "");
}
// console.log(converTimeOfHMS(date))


function formDate(dateForm) {
  if (dateForm === "") {  //解决deteForm为空传1970-01-01 00:00:00
    return "";
  } else {
    var dateee = new Date(dateForm).toJSON();
    var date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
    return date;
  }
}
// console.log(formDate("2022-08-26T23:59:59+08:00"))

</script>

